package com.ruoyi.system.service.impl;

import java.time.LocalTime;
import java.util.*;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Book;
import com.ruoyi.system.domain.TimeSlices;
import com.ruoyi.system.mapper.BookMapper;
import com.ruoyi.system.mapper.TimeSlicesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.FreeTimeMapper;
import com.ruoyi.system.domain.FreeTime;
import com.ruoyi.system.service.IFreeTimeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 空闲时间(用于切片的)Service业务层处理
 *
 * @author Wu Zhongfu
 * @date 2022-02-03
 */
@Service
public class FreeTimeServiceImpl implements IFreeTimeService {
    @Autowired
    private FreeTimeMapper freeTimeMapper;

    @Autowired
    private TimeSlicesMapper timeSlicesMapper;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 查询空闲时间(用于切片的)
     *
     * @param id 空闲时间(用于切片的)主键
     * @return 空闲时间(用于切片的)
     */
    @Override
    public FreeTime selectFreeTimeById(Integer id) {
        return freeTimeMapper.selectFreeTimeById(id);
    }

    /**
     * 查询空闲时间(用于切片的)列表
     *
     * @param freeTime 空闲时间(用于切片的)
     * @return 空闲时间(用于切片的)
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FreeTime> selectFreeTimeList(FreeTime freeTime) {
        return freeTimeMapper.selectFreeTimeList(freeTime);
    }

    /**
     * 新增空闲时间(用于切片的)
     *
     * @param freeTime 空闲时间(用于切片的)
     * @return 结果
     */
    @Override
    @Transactional
    public int insertFreeTime(FreeTime freeTime) throws Exception {
        Long userId = freeTime.getUserId();
        if (userId == null || userId == 0) {
            freeTime.setUserId(SecurityUtils.getUserId());
        }
        FreeTime temFree = new FreeTime();
        temFree.setUserId(freeTime.getUserId());
        temFree.setDateRange1(freeTime.getDateRange1());
        temFree.setDateRange2(freeTime.getDateRange2());
        temFree.setMorning1(freeTime.getMorning1());
        temFree.setMorning2(freeTime.getMorning2());
        temFree.setAfternoon1(freeTime.getAfternoon1());
        temFree.setAfternoon2(freeTime.getAfternoon2());
        List<FreeTime> interSectFreeTime = freeTimeMapper.selectInterSectFreeTime(temFree);
        if (interSectFreeTime.size() > 0) {
            throw new Exception("该用户当前存在日期时间上冲突的空闲时间段");
        }
        int row = freeTimeMapper.insertFreeTime(freeTime);
        cutSlices(freeTime);
        return row;
    }

    public void cutSlices(FreeTime freeTime) {
        Integer noHoliday = freeTime.getNoHoliday();
        Map<Integer, Set<String>> map = new HashMap<>();
        Date dateRange1 = freeTime.getDateRange1();
        long time1 = dateRange1.getTime();
        Date dateRange2 = freeTime.getDateRange2();
        long time2 = dateRange2.getTime();
        for (long i = time1; i <= time2; i += 24 * 3600000) {
            Date date = new Date(i);
            if (noHoliday != 1 || !DateUtils.isHoliday(date, map)) {
                Integer unit = freeTime.getUnit();
                TimeSlices timeSlices = new TimeSlices();
                timeSlices.setFreeTimeId(freeTime.getId());
                timeSlices.setNumBooked(0);
                timeSlices.setBookDate(date);

                //插入上午时间片
                String morning1 = freeTime.getMorning1();
                String morning2 = freeTime.getMorning2();
                if (morning1 != null && morning1.trim().length() > 0 && morning2 != null && morning2.trim().length() > 0) {
                    LocalTime parseMorning1 = LocalTime.parse(morning1);
                    LocalTime parseMorning2 = LocalTime.parse(morning2);
                    parseMorning1 = parseMorning1.plusMinutes(unit);
                    for (; parseMorning1.compareTo(parseMorning2) <= 0; parseMorning1 = parseMorning1.plusMinutes(unit)) {
                        LocalTime localTime1 = parseMorning1.minusMinutes(unit);
                        timeSlices.setStartTime(localTime1.toString());
                        timeSlices.setEndTime(parseMorning1.toString());
                        timeSlicesMapper.insertTimeSlices(timeSlices);
                    }
                }

                //插入下午时间片
                String afternoon1 = freeTime.getAfternoon1();
                String afternoon2 = freeTime.getAfternoon2();
                if (afternoon1 != null && afternoon1.trim().length() > 0 && afternoon2 != null && afternoon2.trim().length() > 0) {
                    LocalTime parseAfternoon1 = LocalTime.parse(afternoon1);
                    LocalTime parseAfternoon2 = LocalTime.parse(afternoon2);
                    parseAfternoon1 = parseAfternoon1.plusMinutes(unit);
                    for (; parseAfternoon1.compareTo(parseAfternoon2) <= 0; parseAfternoon1 = parseAfternoon1.plusMinutes(unit)) {
                        LocalTime localTime1 = parseAfternoon1.minusMinutes(unit);
                        timeSlices.setStartTime(localTime1.toString());
                        timeSlices.setEndTime(parseAfternoon1.toString());
                        timeSlicesMapper.insertTimeSlices(timeSlices);
                    }
                }


            }
        }


    }

    /**
     * 修改空闲时间(用于切片的)
     *
     * @param freeTime 空闲时间(用于切片的)
     * @return 结果
     */
    @Override
    @Transactional
    public int updateFreeTime(FreeTime freeTime) throws Exception {
        FreeTime temFree = new FreeTime();
        temFree.setUserId(freeTime.getUserId());
        temFree.setDateRange1(freeTime.getDateRange1());
        temFree.setDateRange2(freeTime.getDateRange2());
        temFree.setMorning1(freeTime.getMorning1());
        temFree.setMorning2(freeTime.getMorning2());
        temFree.setAfternoon1(freeTime.getAfternoon1());
        temFree.setAfternoon2(freeTime.getAfternoon2());
        List<FreeTime> interSectFreeTime = freeTimeMapper.selectInterSectFreeTime(temFree);
        if (interSectFreeTime.size() > 1 || interSectFreeTime.size() == 1 && !interSectFreeTime.get(0).getId().equals(freeTime.getId())) {
            throw new Exception("该用户当前存在日期时间上冲突的空闲时间段");
        }

        FreeTime freeTimeNow = freeTimeMapper.selectFreeTimeById(freeTime.getId());
        if (!freeTimeNow.getDateRange1().equals(freeTime.getDateRange1())
                || !freeTimeNow.getDateRange2().equals(freeTime.getDateRange2())
                || !freeTimeNow.getMorning1().equals(freeTime.getMorning1())
                || !freeTimeNow.getMorning2().equals(freeTime.getMorning2())
                || !freeTimeNow.getAfternoon1().equals(freeTime.getAfternoon1())
                || !freeTimeNow.getAfternoon2().equals(freeTime.getAfternoon2())
                || !freeTimeNow.getUnit().equals(freeTime.getUnit())
                || !freeTimeNow.getNoHoliday().equals(freeTime.getNoHoliday())
        ) {
            Book book = new Book();
            book.setFreeTimeId(freeTime.getId());
            book.setStatus(0);
            List<Book> books = bookMapper.selectNotStartByFreeId(book);
            if (books.size()>0) {
                throw new Exception("该时间段存在未开始的预约，不能更改涉及日期和时间的信息");
            }
            timeSlicesMapper.deleteTimeSlicesByFreeId(freeTime.getId());
            cutSlices(freeTime);
        }
        return freeTimeMapper.updateFreeTime(freeTime);
    }

    /**
     * 批量删除空闲时间(用于切片的)
     *
     * @param ids 需要删除的空闲时间(用于切片的)主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFreeTimeByIds(Integer[] ids) {
        timeSlicesMapper.deleteTimeSlicesByFreeIds(Arrays.asList(ids));
        return freeTimeMapper.deleteFreeTimeByIds(ids);
    }

    /**
     * 删除空闲时间(用于切片的)信息
     *
     * @param id 空闲时间(用于切片的)主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFreeTimeById(Integer id) {
        timeSlicesMapper.deleteTimeSlicesByFreeId(id);
        return freeTimeMapper.deleteFreeTimeById(id);
    }
}
